import os
from lightrag import LightRAG, QueryParam
from lightrag.base import QueryParam
from lightrag.llm import openai_complete_if_cache
from lightrag.utils import EmbeddingFunc
import numpy as np
from dotenv import load_dotenv
load_dotenv()
from ApiTools import apiBase,apiTools

llm = apiTools.llm
vectdb = apiTools.load_vec()
#########
# Uncomment the below two lines if running in a jupyter notebook to handle the async nature of rag.insert()
import nest_asyncio
nest_asyncio.apply()
#########

WORKING_DIR = "./light_graph"
if not os.path.exists(WORKING_DIR):
    os.mkdir(WORKING_DIR)

async def llm_model_func(
    prompt, system_prompt=None, history_messages=[], **kwargs
) -> str:
    return  apiTools.complete(system_prompt,prompt)

async def embedding_func(texts: list[str]) -> np.ndarray:
    return apiBase.vector_embed(texts)
    
rag = LightRAG(
    working_dir=WORKING_DIR,
    llm_model_func=llm_model_func , # Use gpt_4o_mini_complete LLM model
    embedding_func=EmbeddingFunc(
        embedding_dim=512,
        max_token_size=8192,
        func=embedding_func
    )
)
with open("./book.txt") as f:
    rag.insert(f.read())
    
#rag.insert(["TEXT1", "TEXT2",...])

# Perform naive search
print(rag.query("What are the top themes in this story?", param=QueryParam(mode="naive")))

# Perform local search
print(rag.query("What are the top themes in this story?", param=QueryParam(mode="local")))

# Perform global search
print(rag.query("What are the top themes in this story?", param=QueryParam(mode="global")))

# Perform hybrid search
print(rag.query("What are the top themes in this story?", param=QueryParam(mode="hybrid")))